import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import update from 'react-addons-update';
import { Toast, Modal } from 'antd-mobile';
import Utils from '../../../utils/index'
import DB from '../../../app/db';
import StorageUtils from '../../../app/storage'
import { Control } from 'react-keeper'
import arrayTreeFilter from "array-tree-filter";

let timer;
export default Reflux.createStore({
  listenables: [Actions],
  data: {
    ...PageConst,
    showWarn: false,
    warnTimer: null,
    codeTimer: null,
    warnMessage: '',
    count: 60,
    showCodeTimer: true,
    vcode: '',
    showCertOK:false,
    showPhoneOK:false,
    phone: '',
    sValue: [],
    zValue:[],
    showValue:[],
    seasons:[[]],
    seasonsValue: [],
    currentCour:{},
    userInfo: {
      id:'',
      name:'',
      phone:'',
      doors:[],
      courts:[],
      propris:[],
      state:'',
      priType:'',
      certNum: '',
      vcode: ''
    },
    info: {
      certNum: '请输入身份证号码',
      name: '',
      tel: '',
      court: {},
      editable: true
    },
    inputStatus: {
      certNum: null,
      certNumEditable: true,
      identifyingCodeEditable: false,
      identifyingCode: null,
      identifyingButton: {
        value: '获取验证码',
        disabled: true,
        expireTime: 0
      },
      registerDisabled: true
    }
  },

  init() {
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getUser()}});
    this.updateComponent();
  },

  initInfo() {

    let expireTime = StorageUtils.getStorageItem('ExpireTime');

    if (expireTime) {
      if (StorageUtils.getStorage().has('VCStartTime')) {
        let vcStartTime = StorageUtils.getStorageItem('VCStartTime');
        let vcEndTime = new Date().getTime();
        expireTime = 60 - Math.floor((vcEndTime - vcStartTime) / 1000);
        StorageUtils.setStorage('ExpireTime', expireTime);
      }
    }

    if (expireTime && expireTime > 0) {
      this.data.inputStatus = update(this.data.inputStatus, {
        identifyingButton: {
          value: {$set: "重新获取(" + expireTime + "秒)"},
          disabled: {$set: true},
          expireTime: {$set: expireTime}
        }
      });
      this.updateComponent();
      timer = setInterval(function () {
        t.countDown();
      }, 1000);
    } else {
      StorageUtils.removeStorageItem('VCStartTime');
      this.data.inputStatus = update(this.data.inputStatus, {
        certNum: {$set: null},
        certNumEditable: {$set: true},
        identifyingCodeEditable: {$set: false},
        identifyingCode: {$set: null},
        identifyingButton: {
          value: {$set: '获取验证码'},
          disabled: {$set: true},
          expireTime: {$set: 0}
        },
        registerDisabled: {$set: true}
      });
    }
    let t = this;
    let proprietor = StorageUtils.getStorageItem('proprietor');
    if (proprietor && proprietor.id) {
      let info = {
        certNum: proprietor.identityCard,
        name: proprietor.name,
        tel: proprietor.phone,
        editable: false
      };
      t.data.info = update(t.data.info, {$merge: info});
      t.updateComponent();
    } else {
      let userInfo = StorageUtils.getUser();
      DB.WechatAPI.getProprietorByOpenId({openId: userInfo.openId}).then(
        function (content) {
          if (content && content.id) {
            StorageUtils.updateUser({proprietorId: content.id});
            StorageUtils.setStorage('proprietor', content);
            let info = {
              certNum: content.identityCard,
              name: content.name,
              tel: content.phone,
              editable: false
            };
            t.data.info = update(t.data.info, {$merge: info});
            t.updateComponent();
          }
        },
        function (error) {
          console.log(error);
        }
      );
    }
  },

  initMode: function () {
    let t = this;
    this.data.seasons = update(this.data.seasons, {$set: [[]]});
    this.data.seasonsValue = update(this.data.seasonsValue, {$set: []});
    this.data.zValue = update(this.data.zValue, {$set: []});
    this.data.propris = update(this.data.propris, {$set: []});
    this.data.userInfo = update(this.data.userInfo, {certNum: {$set: ''}});

    //this.onloadCourt();
  },

  initUser: function () {
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getStorage().get('user')}});
    this.updateComponent();
  },


  onChangeCurt: function (v) {
    this.data.zValue = update(this.data.zValue,  {$set: v});
    const value = v;
    if (!value) {
      return '';
    }
    const treeChildren = arrayTreeFilter(this.data.seasons[0], (c, level) => c.value === value[level]);
    let s = treeChildren.map(v => v.label).join(',');
    this.data.showValue = update(this.data.showValue,  {$set: [s]});

    this.updateComponent();
  },

  onSetCurt: function (e) {
    this.data.info = update(this.data.info, {court: {$set: e}});
    this.updateComponent();
  },

  onloadCourt: function () {

    let t = this;
    DB.WechatAPI.findCourtByPhone({
      phone: this.data.userInfo.phone,
    }).then(
      function (content) {
        let resultObj = Utils.isEmptyObject(content);
        if (resultObj.success) {
          t.data.courts = update(t.data.courts,  {$set: content});
          console.log(t.data.courts);
          t.data.courts.forEach(function(value,index,array){
            t.data.seasonsValue.push({
              label:value.name,
              value: value.id,
            })
          });
          t.data.seasons[0] = t.data.seasonsValue;
          t.updateComponent();
        }

      },
      function (error) {
        console.log(error);
      });
  },

  onCheckCertNum: function (e) {

    let t = this;
    let resultCertNum = Utils.checkCard(this.data.userInfo.certNum);
    if (!resultCertNum.success) {
      console.log(resultCertNum);
      this.showWarnMessage(e,resultCertNum.message);
      return;
    }

    if (resultCertNum.success) {
      DB.WechatAPI.checkUserCertNum({
        cert: this.data.userInfo.certNum,
      }).then(
        function (content) {
          let resultObj = Utils.isEmptyObject(content);
          console.info(resultObj.success);
          if (!resultObj.success) {
            t.showWarnMessage(e,'用户未注册');
          }
          else
          {
            t.data.userInfo = update(t.data.userInfo, {telNum: {$set: content.phone}});
            let resultPhone = Utils.checkPhone(t.data.userInfo.telNum);
            if (resultPhone.success) {
              t.data.showPhoneOK = update(t.data.showPhoneOK, {$set: true});
              t.data.showCertOK = update(t.data.showCertOK, {$set: true});
              t.data.userInfo = update(t.data.userInfo, {telNum: {$set: content.phone}});
              t.data.phone = update(t.data.phone,  {$set: t.data.userInfo.telNum});

              t.data.userInfo = update(t.data.userInfo, {phone: {$set: content.phone}});
              t.data.userInfo = update(t.data.userInfo, {name: {$set: content.name}});
              t.data.userInfo = update(t.data.userInfo, {state: {$set: content.state}});
              t.data.userInfo = update(t.data.userInfo, {priType: {$set: content.priType}});

              console.log(t.data.userInfo);
              StorageUtils.upUser(t.data.userInfo);

              DB.WechatAPI.binding(t.data.userInfo).then(
                function (content) {
                  Control.go('/home/my');
                },
                function (error) {
                  console.log(error);
                });

              t.updateComponent();
            }
            else {
              t.data.userInfo = update(t.data.userInfo, {phone: {$set: content.phone}});
              t.data.userInfo = update(t.data.userInfo, {name: {$set: content.name}});
              t.data.userInfo = update(t.data.userInfo, {state: {$set: content.state}});
              t.data.userInfo = update(t.data.userInfo, {priType: {$set: content.priType}});
              t.data.userInfo = update(t.data.userInfo, {id: {$set: content.id}});
              console.log('不严重');
              console.log(t.data.userInfo);
              StorageUtils.upUser(t.data.userInfo);
              Control.replace('/home/my');
            }

            console.log(content);

            t.updateComponent();
          }

        },
        function (error) {
          console.info('11_erro');
          console.log(error);
        });
    }
  },

  onEnterInfo: function (param) {
    let t = this;
    /*if (!param.court.id) {
      Toast.fail('小区未选择', 3);
      return false;
    }*/
    let certNum = this.data.info.certNum;
    if (!certNum && certNum === '') {
      Toast.fail('请输入身份证', 3);
      return false;
    }

    DB.WechatAPI.checkUserCard({
      card: certNum,
    }).then(
      function (content) {
        let resultObj = Utils.isEmptyObject(content);
        if (!resultObj.success) {
          Toast.fail('您提供的身份证没有找到房产信息', 2);
          // t.showWarnMessage(e,'用户未注册');
        } else {
          let params = {
            card: certNum,
            // courtId: param.court.id,
            openId: t.data.userInfo.openId
          };
          DB.WechatAPI.bindDoor(params).then(
            function (content) {
              DB.WechatAPI.binding({
                card: certNum,
                openId: t.data.userInfo.openId
              }).then(
                function (binding) {
                  Toast.fail('绑定小区成功', 2);
                  Control.replace('/home/my');
                },
                function (error) {
                  console.log(error);
                });
            },
            function (error) {
              console.log(error);
              alert(error.message);
            });
        }

      },
      function (error) {
        console.log(error);
        alert(JSON.stringify(error));
      });
  },

  doRegister() {
    let t = this;
    let certNum = t.data.inputStatus.certNum;
    let params = {
      card: certNum,
      openId: t.data.userInfo.openId
    };
    DB.WechatAPI.bindDoor(params).then(
      function (content) {
        DB.WechatAPI.binding({
          card: certNum,
          openId: t.data.userInfo.openId
        }).then(
          function (binding) {
            Toast.fail('绑定小区成功', 2);
            Control.replace('/home/my');
          },
          function (error) {
            console.log(error);
          });
      },
      function (error) {
        console.log(error);
        alert(error.message);
      }
    );
  },

  showWarnMessage: function (e,message) {
    Toast.info(message, 1);
  },

  onChangeCertNum: function (certNum) {
    let info = this.data.info;
    info.certNum = certNum;
    this.data.info = update(this.data.info, {$set: info});
    this.updateComponent();
  },


  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  },

  onInputCertNum(certNum) {
    this.data.inputStatus.certNum = update(this.data.inputStatus.certNum, {$set: certNum});
    this.updateComponent();
    if (Utils.isCardID(certNum)) {
      this.data.inputStatus = update(this.data.inputStatus, {
        identifyingCodeEditable: {$set: true},
        identifyingButton: {
          disabled: {$set: false}
        }
      });
    } else {
      this.data.inputStatus = update(this.data.inputStatus, {
        identifyingCodeEditable: {$set: false},
        identifyingButton: {
          disabled: {$set: true}
        }
      });
    }
    this.updateComponent();
  },

  onBlurCertNumber(certNum) {
    if (Utils.isCardID(certNum)) {
    } else {
      Toast.fail('身份证号码错误！', 1);
    }
  },

  onInputIdentifyingCode(code) {
    this.data.inputStatus.identifyingCode = update(this.data.inputStatus.identifyingCode, {$set: code});
    this.updateComponent();
    if (code && code.length === 6) {
      this.data.inputStatus.registerDisabled = update(this.data.inputStatus.registerDisabled, {$set: false});
    } else {
      this.data.inputStatus.registerDisabled = update(this.data.inputStatus.registerDisabled, {$set: true});
    }
    this.updateComponent();
  },

  countDown() {
    let expireTime = StorageUtils.getIdentifyInfoItem('ExpireTime');
    let identifyingButton = {};
    if (expireTime === 0) {
      identifyingButton = {
        disabled: false,
        expireTime: 60,
        value: '重新获取'
      };
      this.data.inputStatus.certNumEditable = update(this.data.inputStatus.certNumEditable, {$set: true});
      this.data.inputStatus.identifyingButton = update(this.data.inputStatus.identifyingButton, {$set: identifyingButton});
      this.updateComponent();
      clearInterval(timer);
      StorageUtils.removeIdentifyInfoItem('ExpireTime');
      // StorageUtils.removeIdentifyInfoItem('IdentifyingCode');
    } else {
      expireTime--;
      identifyingButton = {
        disabled: true,
        expireTime: expireTime,
        value: "重新获取(" + expireTime + "秒)"
      };
      this.data.inputStatus.identifyingButton = update(this.data.inputStatus.identifyingButton, {$set: identifyingButton});
      this.updateComponent();
      StorageUtils.setIdentifyInfo('ExpireTime', expireTime);
    }
  },

  sendIdentifyingCode() {
    let t = this;
    if (Utils.isCardID(t.data.inputStatus.certNum)) {
      t.data.inputStatus.identifyingButton = update(t.data.inputStatus.identifyingButton, {
        disabled: {$set: true}
      });
      t.updateComponent();
      DB.WechatAPI.getPhoneNumberByCertNum({certNum: t.data.inputStatus.certNum}).then(
        function (content) {
          if (Utils.checkMobilePhone(content)) {
            let phone = content;
            let vcode = Utils.createCode();
            StorageUtils.setIdentifyInfo('IdentifyingCode', vcode);
            DB.WechatAPI.sendVCodeMessage({
              phone: phone,
              vcode: vcode
            }).then(
              function (content) {
                StorageUtils.setIdentifyInfo('VCStartTime', new Date().getTime());
                StorageUtils.setIdentifyInfo('ExpireTime', 60);
                let identifyingButton = t.data.inputStatus.identifyingButton;
                if (identifyingButton.expireTime === 0) {
                  t.data.inputStatus = update(t.data.inputStatus, {
                    certNumEditable: {$set: false},
                    identifyingCodeEditable: {$set: true},
                    identifyingCode: {$set: null},
                    identifyingButton: {
                      expireTime: {$set: StorageUtils.getIdentifyInfoItem('ExpireTime')}
                    }
                  });
                }
                t.updateComponent();
                timer = setInterval(function () {
                  t.countDown();
                }, 1000);

                let phoneStr = phone.toString();
                Modal.alert(
                  '提示',
                  '已向手机号'+phoneStr.substr(0, 3)+'****'+phoneStr.substr(7)+'发送验证码，请注意查收。',
                  [
                    {text: '确认'}
                  ]);
              },
              function (error) {
                t.data.inputStatus.identifyingButton = update(t.data.inputStatus.identifyingButton, {
                  disabled: {$set: false}
                });
                t.updateComponent();
                Toast.fail('验证码发送失败。');
              }
            );
          } else {
            t.data.inputStatus.identifyingButton = update(t.data.inputStatus.identifyingButton, {
              disabled: {$set: false}
            });
            t.updateComponent();
            Toast.fail('您输入的身份证号没有匹配到手机号码。')
          }
        },
        function (error) {
          t.data.inputStatus.identifyingButton = update(t.data.inputStatus.identifyingButton, {
            disabled: {$set: false}
          });
          t.updateComponent();
          Toast.fail(error.message);
        }
      );
    } else {
      Toast.fail('身份证号码有误');
    }
  },

  doValidate() {
    let identifyingCode = StorageUtils.getIdentifyInfoItem('IdentifyingCode');
    if (identifyingCode) {
      if (identifyingCode === this.data.inputStatus.identifyingCode) {
        if (timer) {
          clearInterval(timer);
        }

        this.data.inputStatus = update(this.data.inputStatus, {
          certNumEditable: {$set: true},
          identifyingCodeEditable: {$set: false},
          identifyingButton: {
            value: {$set: '获取验证码'},
            disabled: {$set: true},
            expireTime: {$set: 0}
          },
          registerDisabled: {$set: true}
        });
        this.updateComponent();
        StorageUtils.removeIdentifyInfoItem('VCStartTime');
        StorageUtils.removeIdentifyInfoItem('ExpireTime');

        DB.WechatAPI.register({
          certNum: this.data.inputStatus.certNum,
          openId: StorageUtils.getStorageItem('user').openId
        }).then(
          function (content) {
            if (content) {
              Toast.success('认证通过');
              StorageUtils.removeIdentifyInfoItem('IdentifyingCode');
              Control.replace('/home/my');
            } else {
              Toast.fail('认证失败');
            }
          },
          function (error) {
            Toast.info('系统故障');
          }
        );
      } else {
        Toast.fail('验证码错误！');
      }
    } else {
      Toast.fail('验证码失效，请重新获取验证码！')
    }

  }

});
